var optfile = require('./optfile');
var url = require('url');
var querystring = require('querystring'); //post需要导入

function getRecall(req, res) {
  res.writeHead(200, {'Content-Type': 'text/html; charset=utf-8'});
  function recall (data) {
    res.write(data);
    res.end();
  }
  return recall;
}

module.exports = {
  login: function (req, res) {
    //-----get方式接收参----------
    /*
    var rdata = url.parse(req.url, true).query;
    console.log(rdata);
    if(rdata['email'] != undefined) {
      console.log(rdata['email']);
      console.log(rdata['pwd']);
    }
    */

    //---------post方式接收参数--------
    var post = ''; //定义了一个post变量，用于暂存请求体信息
    req.on('data', function (chunk) { // 通过req的data事件监听函数，每当接收到请求体的数据，就到post变量中
      post += chunk;
    });
    //-----注意异步-------
    req.on('end', function () {  //在end事件触发后，通过que
      post = querystring.parse(post);
      console.log('收到email参数:' + post['email'] + '\n');
      console.log('收到password参数:' + post['pwd'] + '\n');
      arr = ['email','pwd'];
      //recall = getRecall(req, res);
      function recall(data) {
        dataStr = data.toString();
        for(var i = 0; i < arr.length; i++) {
          re = new RegExp('{'+arr[i]+'}','g');
          dataStr = dataStr.replace(re, post[arr[i]]);
        }
        res.write(dataStr);
        res.end();
      }
      optfile.readfile('./views/login.html', recall);
    });
  },
  regist: function (req, res) {
    recall = getRecall(req, res);
    optfile.readfile('./views/regist.html', recall);
  },
  writefile: function (req, res) {
    function recall(data) {
      res.write(data);
      res.end();
    }
    optfile.writefile('./views/one.txt','我的写入文件',recall);
  },
  showimg: function (req, res) {
    res.writeHead(200, {'Content-Type': 'image/jpeg'});
    optfile.readImg('./imgs/demo.jpeg', res);
  }
}
